<?php

class DomainMapper
{

  public static function inflate($model, $data, $obj = null)
  {
    $_model = Domain::getObject($model);

    $id = $_model->getField($_model->getPk())->getName();

    $_data = array();
    foreach ($_model->getFields() as $name => $__model) {
      $field = $_model->getField($name);

      $_data[$name] = self::inflateField($field, isset($data[$field->getName()]) ? $data[$field->getName()] : null);
    }

    if (empty($obj)) {
      $obj = $_model->factory($model, $_data);
    }

    if (! empty($id)) {
      $obj->commit();
    }

    return $obj;
  }

  public static function inflateField($model, $value)
  {
    if (! ($model instanceof FieldModel)) {
      $model = new FieldModel($model);
    }

    $mapper = $model->getMapper();

    if (! empty($mapper)) {
      $value = $mapper->inflate($value);
    }

    return $value;
  }

  public static function deflateField($model, $value)
  {
    if (! ($model instanceof FieldModel)) {
      $model = new FieldModel($model);
    }

    $mapper = $model->getMapper();

    if (! empty($mapper)) {
      $value = $mapper->deflate($value);
    }

    return $value;
  }

}
